package com.example.wifi4server;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int DEVICE_CONNECTING = 1;//有设备正在连接热点
    public static final int DEVICE_CONNECTED = 2;//有设备连上热点
    public static final int SEND_MSG_SUCCSEE = 3;//发送消息成功
    public static final int SEND_MSG_ERROR = 4;//发送消息失败
    public static final int GET_MSG = 6;//获取新消息
    public static final int REOPEN_SSID = 7;

    private TextView text_state;
    private WifiManager wifiManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.create_wifi).setOnClickListener(this);
        findViewById(R.id.close_wifi).setOnClickListener(this);
        findViewById(R.id.send).setOnClickListener(this);
        text_state = (TextView) findViewById(R.id.receive);

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        mListenerTask = new ListenerTask(PORT, mHandler);
        ThreadPoolManager.THREAD_POOL_EXECUTOR.execute(mListenerTask);
    }

    private ListenerTask mListenerTask;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.create_wifi:
                mListenerTask.bStop = true;
                ThreadPoolManager.THREAD_POOL_EXECUTOR.execute(new CloseSocketTask(mListenerTask, false));
                boolean bCreatedWifi = createWifiHotspot();
                mListenerTask = new ListenerTask(PORT, mHandler);
                ThreadPoolManager.THREAD_POOL_EXECUTOR.execute(mListenerTask);
                break;
            case R.id.send:
                String strmsg = "111这是来自Wifi热点的消息";
                for (Socket socket : mListenerTask.mListConnectSocket) {
                    WriteTask writeTask = new WriteTask(socket, strmsg, mHandler);
                    mListenerTask.mListWriteTask.add(writeTask);
                    ThreadPoolManager.THREAD_POOL_EXECUTOR.execute(writeTask);
                }
                break;
            case R.id.close_wifi:
                mListenerTask.bStop = true;
                ThreadPoolManager.THREAD_POOL_EXECUTOR.execute(new CloseSocketTask(mListenerTask, false));
                closeWifiHotspot();
                break;
        }
    }

    public void closeWifiHotspot() {
        try {
            Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");
            method.setAccessible(true);
            WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager);
            Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            method2.invoke(wifiManager, config, false);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        text_state.setText("热点已关闭");
    }

    @Override
    protected void onDestroy() {
        mListenerTask.bStop = true;
        super.onDestroy();
        System.exit(0);
    }


    private static final String WIFI_HOTS_SSID = "TEST";
    private static final int PORT = 54321;

    private boolean createWifiHotspot() {
        boolean bRet = false;
        if (wifiManager.isWifiEnabled())
            wifiManager.setWifiEnabled(false); //如果wifi处于打开状态，则关闭wifi,

        final WifiConfiguration config = new WifiConfiguration();
        config.SSID = WIFI_HOTS_SSID;
        config.preSharedKey = "123456789";
        config.hiddenSSID = false;
        config.allowedAuthAlgorithms
                .set(WifiConfiguration.AuthAlgorithm.OPEN);//开放系统认证
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        config.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedPairwiseCiphers
                .set(WifiConfiguration.PairwiseCipher.CCMP);
        config.status = WifiConfiguration.Status.ENABLED;

        String strTxt = ""; //通过反射调用设置热点
        try {
            Method method = wifiManager.getClass().getMethod(
                    "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
            boolean bEnable = (Boolean) method.invoke(wifiManager, config, true);
            strTxt = (bEnable) ? "热点已开启 SSID:" + WIFI_HOTS_SSID + " password:123456789" : "创建热点失败";
        } catch (Exception e) {
            e.printStackTrace();
            strTxt = "创建热点失败";
        }
        text_state.setText(strTxt);
        return bRet;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DEVICE_CONNECTING:
                    break;
                case DEVICE_CONNECTED:
                    text_state.setText("设备连接成功");
                    break;
                case SEND_MSG_SUCCSEE:
                    text_state.setText("发送消息成功:" + msg.getData().getString("MSG"));
                    break;
                case SEND_MSG_ERROR:
                    text_state.setText("发送消息失败:" + msg.getData().getString("MSG"));
                    break;
                case GET_MSG:
                    text_state.setText("收到消息:" + msg.getData().getString("MSG"));
                    break;
                case REOPEN_SSID:
                    boolean bCreatedWifi = createWifiHotspot();
                    if (bCreatedWifi == true) {
                        mListenerTask = new ListenerTask(PORT, mHandler);
                        ThreadPoolManager.THREAD_POOL_EXECUTOR.execute(mListenerTask);
                    }
                    break;
            }
        }
    };
}